<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/07/27 07:39:17 $)
// $RCSfile: functions_ticketsui.php,v $ : $Revision: 1.36 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

define("FIELD_TICKETID", 1);
define("FIELD_TICKETMASKID", 2);
define("FIELD_SUBJECT", 3);
define("FIELD_QUEUE", 4);
define("FIELD_DEPARTMENT", 5);
define("FIELD_TICKETSTATUS", 6);
define("FIELD_DUEDATE", 7);
define("FIELD_LASTACTIVITY", 8);
define("FIELD_DATE", 9);
define("FIELD_OWNER", 10);
define("FIELD_PRIORITY", 11);
define("FIELD_LASTREPLIER", 12);
define("FIELD_FULLNAME", 13);
define("FIELD_TIMEWORKED", 14);
define("FIELD_EMAIL", 15);
define("FIELD_REPLIES", 16);
define("FIELD_FLAGS", 17);
define("FIELD_ASSIGNSTATUS", 18);
define("FIELD_DATEICON", 19);
define("FIELD_NOTESTATUS", 20);
define("FIELD_LASTSTAFFREPLY", 21);
define("FIELD_TGROUP", 22);

define("TICKETGRID_LIMIT", 1);
define("TICKETGRID_SORTORDER", 2);
define("TICKETGRID_SORTBY", 3);
define("TICKETGRID_TOTALITEMS", 4);

global $_fieldpointer;
$_fieldpointer = array();
$_fieldpointer[FIELD_TICKETID]["name"] = "t.ticketid";
$_fieldpointer[FIELD_TICKETID]["title"] = $_SWIFT["language"]["f_ticketid"];
$_fieldpointer[FIELD_TICKETID]["width"] = "80";
$_fieldpointer[FIELD_TICKETID]["align"] = "center";

$_fieldpointer[FIELD_DATEICON]["name"] = "t.dateicon";
$_fieldpointer[FIELD_DATEICON]["title"] = $_SWIFT["language"]["f_dateicon"];
$_fieldpointer[FIELD_DATEICON]["width"] = "18";
$_fieldpointer[FIELD_DATEICON]["align"] = "center";
$_fieldpointer[FIELD_DATEICON]["space"] = true;

$_fieldpointer[FIELD_NOTESTATUS]["name"] = "t.hasnotes";
$_fieldpointer[FIELD_NOTESTATUS]["title"] = $_SWIFT["language"]["f_hasnotes"];
$_fieldpointer[FIELD_NOTESTATUS]["width"] = "18";
$_fieldpointer[FIELD_NOTESTATUS]["align"] = "center";
$_fieldpointer[FIELD_NOTESTATUS]["space"] = true;

$_fieldpointer[FIELD_SUBJECT]["name"] = "t.subject";
$_fieldpointer[FIELD_SUBJECT]["title"] = $_SWIFT["language"]["f_subject"];
$_fieldpointer[FIELD_SUBJECT]["width"] = "";
$_fieldpointer[FIELD_SUBJECT]["align"] = "left";

$_fieldpointer[FIELD_QUEUE]["name"] = "t.emailqueueid";
$_fieldpointer[FIELD_QUEUE]["title"] = $_SWIFT["language"]["f_queue"];
$_fieldpointer[FIELD_QUEUE]["width"] = "180";
$_fieldpointer[FIELD_QUEUE]["align"] = "center";

$_fieldpointer[FIELD_DEPARTMENT]["name"] = "t.departmentid";
$_fieldpointer[FIELD_DEPARTMENT]["title"] = $_SWIFT["language"]["f_department"];
$_fieldpointer[FIELD_DEPARTMENT]["width"] = "120";
$_fieldpointer[FIELD_DEPARTMENT]["align"] = "center";

$_fieldpointer[FIELD_TICKETSTATUS]["name"] = "t.ticketstatusid";
$_fieldpointer[FIELD_TICKETSTATUS]["title"] = $_SWIFT["language"]["f_ticketstatus"];
$_fieldpointer[FIELD_TICKETSTATUS]["width"] = "100";
$_fieldpointer[FIELD_TICKETSTATUS]["align"] = "center";

$_fieldpointer[FIELD_DUEDATE]["name"] = "t.duetime";
$_fieldpointer[FIELD_DUEDATE]["title"] = $_SWIFT["language"]["f_duedate"];
$_fieldpointer[FIELD_DUEDATE]["width"] = "80";
$_fieldpointer[FIELD_DUEDATE]["align"] = "center";

$_fieldpointer[FIELD_LASTACTIVITY]["name"] = "t.lastactivity";
$_fieldpointer[FIELD_LASTACTIVITY]["title"] = $_SWIFT["language"]["f_lastactivity"];
$_fieldpointer[FIELD_LASTACTIVITY]["width"] = "100";
$_fieldpointer[FIELD_LASTACTIVITY]["align"] = "center";

$_fieldpointer[FIELD_DATE]["name"] = "t.dateline";
$_fieldpointer[FIELD_DATE]["title"] = $_SWIFT["language"]["f_date"];
$_fieldpointer[FIELD_DATE]["width"] = "160";
$_fieldpointer[FIELD_DATE]["align"] = "center";

$_fieldpointer[FIELD_OWNER]["name"] = "t.ownerstaffid";
$_fieldpointer[FIELD_OWNER]["title"] = $_SWIFT["language"]["f_owner"];
$_fieldpointer[FIELD_OWNER]["width"] = "130";
$_fieldpointer[FIELD_OWNER]["align"] = "center";

$_fieldpointer[FIELD_PRIORITY]["name"] = "t.priorityid";
$_fieldpointer[FIELD_PRIORITY]["title"] = $_SWIFT["language"]["f_priority"];
$_fieldpointer[FIELD_PRIORITY]["width"] = "90";
$_fieldpointer[FIELD_PRIORITY]["align"] = "center";

$_fieldpointer[FIELD_LASTREPLIER]["name"] = "t.lastreplier";
$_fieldpointer[FIELD_LASTREPLIER]["title"] = $_SWIFT["language"]["f_lastreplier"];
$_fieldpointer[FIELD_LASTREPLIER]["width"] = "130";
$_fieldpointer[FIELD_LASTREPLIER]["align"] = "center";

$_fieldpointer[FIELD_FULLNAME]["name"] = "t.fullname";
$_fieldpointer[FIELD_FULLNAME]["title"] = $_SWIFT["language"]["f_fullname"];
$_fieldpointer[FIELD_FULLNAME]["width"] = "140";
$_fieldpointer[FIELD_FULLNAME]["align"] = "center";

$_fieldpointer[FIELD_TIMEWORKED]["name"] = "t.timeworked";
$_fieldpointer[FIELD_TIMEWORKED]["title"] = $_SWIFT["language"]["f_timeworked"];
$_fieldpointer[FIELD_TIMEWORKED]["width"] = "120";
$_fieldpointer[FIELD_TIMEWORKED]["align"] = "center";

$_fieldpointer[FIELD_EMAIL]["name"] = "t.email";
$_fieldpointer[FIELD_EMAIL]["title"] = $_SWIFT["language"]["f_email"];
$_fieldpointer[FIELD_EMAIL]["width"] = "180";
$_fieldpointer[FIELD_EMAIL]["align"] = "center";

$_fieldpointer[FIELD_REPLIES]["name"] = "t.totalreplies";
$_fieldpointer[FIELD_REPLIES]["title"] = $_SWIFT["language"]["f_totalreplies"];
$_fieldpointer[FIELD_REPLIES]["width"] = "70";
$_fieldpointer[FIELD_REPLIES]["align"] = "center";

$_fieldpointer[FIELD_FLAGS]["name"] = "t.flagtype";
$_fieldpointer[FIELD_FLAGS]["title"] = $_SWIFT["language"]["f_flagtype"];
$_fieldpointer[FIELD_FLAGS]["width"] = "18";
$_fieldpointer[FIELD_FLAGS]["align"] = "center";
$_fieldpointer[FIELD_FLAGS]["space"] = true;

$_fieldpointer[FIELD_ASSIGNSTATUS]["name"] = "t.assignstatus";
$_fieldpointer[FIELD_ASSIGNSTATUS]["title"] = $_SWIFT["language"]["f_assignstatus"];
$_fieldpointer[FIELD_ASSIGNSTATUS]["width"] = "100";
$_fieldpointer[FIELD_ASSIGNSTATUS]["align"] = "center";

$_fieldpointer[FIELD_LASTSTAFFREPLY]["name"] = "t.laststaffreplytime";
$_fieldpointer[FIELD_LASTSTAFFREPLY]["title"] = $_SWIFT["language"]["f_laststaffreply"];
$_fieldpointer[FIELD_LASTSTAFFREPLY]["width"] = "80";
$_fieldpointer[FIELD_LASTSTAFFREPLY]["align"] = "center";

$_fieldpointer[FIELD_TGROUP]["name"] = "t.tgroupid";
$_fieldpointer[FIELD_TGROUP]["title"] = $_SWIFT["language"]["f_tgroup"];
$_fieldpointer[FIELD_TGROUP]["width"] = "100";
$_fieldpointer[FIELD_TGROUP]["align"] = "center";



/**
* Renders the Tree for used in ticket list
*/
function renderTicketTree()
{
	global $_SWIFT, $template;

	if ($_SWIFT["staff"]["t_entab"] == "0")
	{
		return false;
	}

	$departmentidlist = getAssignedDepartments(MODULE_TICKETS);

	require_once ("./includes/TreeMenu/TreeMenu.php");
	$template->assign("treemenu", true);
	$icon = 'icon_folderyellow3.gif';
	$expandedIcon = 'icon_folderyellow3.gif';

	$menu = new HTML_TreeMenu();

	$alldeptitle = $_SWIFT["language"]["alldepartments"];

	$departmentnode = &$menu->addItem(new HTML_TreeNode(array('text' => "&nbsp;". $alldeptitle, 'link' => "index.php?_m=tickets&_a=manage", 'icon' => "icon_folderblue2.gif", 'expandedIcon' => "icon_folderblue2.gif")));

	$_filterparent = &$menu->addItem(new HTML_TreeNode(array('text' => "&nbsp;".$_SWIFT["language"]["filters"], 'link' => "index.php?_m=tickets&_a=manage", 'icon' => "icon_funnel.gif", 'expandedIcon' => "icon_funnel.gif")));
	if (_is_array($_SWIFT["ticketfiltercache"]))
	{
		foreach ($_SWIFT["ticketfiltercache"] as $key=>$val)
		{
			if ($val["filtertype"] == SWIFTPUBLIC || ($val["filtertype"] == SWIFTPRIVATE && $val["staffid"] == $_SWIFT["staff"]["staffid"]))
			{
				if ($val["ticketfilterid"] == $_REQUEST["ticketfilterid"] || $_SWIFT["ticketsearch"]["ticketfilterid"] == $val["ticketfilterid"])
				{
					$_filtertitle = '<font color="#3069DC">'.htmlspecialchars($val["title"]).'</font>';
				} else {
					$_filtertitle = htmlspecialchars($val["title"]);
				}

				$_filternode = &$_filterparent->addItem(new HTML_TreeNode(array('text' => "&nbsp;".$_filtertitle, 'link' => "index.php?_m=tickets&_a=runfilter&ticketfilterid=".$val["ticketfilterid"], 'icon' => "icon_treefilteritem.gif", 'expandedIcon' => "icon_treefilteritem.gif")));
			}
		}
	}

	$_labelparent = &$menu->addItem(new HTML_TreeNode(array('text' => "&nbsp;".$_SWIFT["language"]["labels"], 'link' => "index.php?_m=tickets&_a=manage", 'icon' => "icon_labels.gif", 'expandedIcon' => "icon_labels.gif")));
	if (count($_SWIFT["ticketlabelcache"]))
	{
		foreach ($_SWIFT["ticketlabelcache"] as $key=>$val)
		{
			if ($val["ticketlabelid"] == $_REQUEST["ticketlabelid"])
			{
				$_labeltitle = '<font color="#3069DC">'.htmlspecialchars($val["title"]).'</font>';
			} else {
				$_labeltitle = htmlspecialchars($val["title"]);
			}

			unset($_labelcount);
			if (!empty($_SWIFT["labelcountcache"][$val["ticketlabelid"]]))
			{
				$_labelcount = "(".intval($_SWIFT["labelcountcache"][$val["ticketlabelid"]]).")";
			}

			$_labelnode = &$_labelparent->addItem(new HTML_TreeNode(array('text' => "&nbsp;".$_labeltitle."&nbsp;<font color='darkgreen'>". $_labelcount ."</font>", 'link' => "index.php?_m=tickets&_a=manage&ticketlabelid=".$val["ticketlabelid"], 'icon' => "icon_label.gif", 'expandedIcon' => "icon_label.gif")));
		}
	}

	foreach ($_SWIFT["departmentcache"] as $key=>$val)
	{
		if (!is_array($val))
		{
			trigger_error("You do not have permissions to access any department, Contact your Administartor to assign departments", E_USER_ERROR);
			exit;
		}
		if ($val["departmentmodule"] != MODULE_TICKETS || !in_array($val["departmentid"], $departmentidlist))
		{
			continue;
		}

		$ticketcount = "(".$_SWIFT["ticketcountcache"][$val["departmentid"]]["totaltickets"].")";
		if ($ticketcount == "()")
		{
			$ticketcount = "(0)";
		}
		unset($ticketcount);
		if ($_REQUEST["departmentid"] == $val["departmentid"] && $_REQUEST["ticketstatusid"] == "0")
		{
			$departmenttitle = '<font color="#3069DC">'.$val["title"].'</font>';
		} else {
			$departmenttitle = $val["title"];
		}

		if ($_SWIFT["ticketcountcache"][$val["departmentid"]]["lastactivity"] > $_SWIFT["staff"]["lastvisit"])
		{
			$depicon = "icon_folderred.gif";
		} else {
			$depicon = "icon_folderblue2.gif";
		}

		$departmentnode = &$menu->addItem(new HTML_TreeNode(array('text' => "&nbsp;". $departmenttitle."&nbsp;". $ticketcount, 'link' => "index.php?_m=tickets&_a=manage&departmentid=".$val["departmentid"]."&ticketstatusid=0", 'icon' => $depicon, 'expandedIcon' => $depicon)));
		foreach ($_SWIFT["statuscache"] as $statuskey=>$statusval)
		{
			if ($statusval["departmentid"] != 0 && $statusval["departmentid"] != $val["departmentid"])
			{
				continue;
			}

			if ($_SWIFT["ticketcountcache"][$val["departmentid"]][$statusval["ticketstatusid"]]["lastactivity"] > $_SWIFT["staff"]["lastvisit"])
			{
				$statusicon = "icon_redbigdot.gif";
			} else {
				$statusicon = "icon_yellowbigdot.gif";
			}

			$statuscount = "(".number_format($_SWIFT["ticketcountcache"][$val["departmentid"]][$statusval["ticketstatusid"]]["count"],0).")";
			if ($statuscount == "(0)" || $statusval["displaycount"] != 1)
			{
				unset($statuscount);
//				$statuscount = "(0)";
			}
			if ($_REQUEST["ticketstatusid"] == $statusval["ticketstatusid"] && $_REQUEST["departmentid"] == $val["departmentid"])
			{
				$statustitle = '<font color="#3069DC">'.$statusval["title"].'</font>';
			} else {
				$statustitle = $statusval["title"];
			}
			$_statusnode = &$departmentnode->addItem(new HTML_TreeNode(array('text' => "&nbsp;". $statustitle."&nbsp;<font color='darkgreen'>".$statuscount.'</font>', 'link' => "index.php?_m=tickets&_a=manage&departmentid=".$val["departmentid"]."&ticketstatusid=".$statusval["ticketstatusid"], 'icon' => $statusicon, 'expandedIcon' => $statusicon)));

		}
	}

	$treeMenu = &new HTML_TreeMenu_DHTML($menu, array('images' => stripTrailingSlash($_SWIFT["themepath"]), 'defaultClass' => 'treeMenuDefault'));
	ob_start();
	$treeMenu->printMenu();
	$contents = ob_get_contents();
	ob_end_clean();

	$template->assign("tickettree", $contents);
	unset($contents);
}

/**
* Render the ticket grid
*/
function renderTicketGrid($ticketviewid, $departmentidlist, $ticketstatusidlist, $ticketsearchid = false, $ticketlabelid = false)
{
	global $dbCore, $_SWIFT, $datastore, $_fieldpointer, $template;

	ob_start();

	$_ticketview = &$_SWIFT["ticketviewcache"][$ticketviewid];
	if (!is_array($_ticketview))
	{
		trigger_error($_SWIFT["language"]["invalidview"], E_USER_ERROR);
	}

	$appendurl = "&departmentid=". intval($_REQUEST["departmentid"]) ."&ticketstatusid=". intval($_REQUEST["ticketstatusid"]) ."&ticketsearchid=".intval($_REQUEST["ticketsearchid"]);
	$_grid = $_update = array();
	$_gridset = &$_SWIFT["ticketgridcache"][$_SWIFT["staff"]["staffid"]];
	if (!is_array($_gridset))
	{
		$_gridset = array();
		$gridsetupdate = true;
	}
	if ($_POST["opennewwindow"] != $_gridset["opennewwindow"] && trim($_POST["opennewwindow"]) != "")
	{
		$_gridset["opennewwindow"] = $_POST["opennewwindow"];
		$gridsetupdate = true;
	}
	if ($_POST["autorefresh"] != $_gridset["autorefresh"] && trim($_POST["autorefresh"]) != "")
	{
		$_gridset["autorefresh"] = $_POST["autorefresh"];
		$gridsetupdate = true;
	}
	if ($_POST["replynav"] != $_gridset["replynav"] && trim($_POST["replynav"]) != "")
	{
		$_gridset["replynav"] = $_POST["replynav"];
		$gridsetupdate = true;
	}
	if ($_POST["rnticketstatusid"] != $_gridset["rnticketstatusid"] && trim($_POST["rnticketstatusid"]) != "")
	{
		$_gridset["rnticketstatusid"] = $_POST["rnticketstatusid"];
		$gridsetupdate = true;
	}
	if ($_POST["rnsetowner"] != $_gridset["rnsetowner"] && trim($_POST["rnsetowner"]) != "")
	{
		$_gridset["rnsetowner"] = $_POST["rnsetowner"];
		$gridsetupdate = true;
	}
	$_staffid = &$_SWIFT["staff"]["staffid"];

	$_limit = $_ticketview["ticketsperpage"];
	if (!$_limit)
	{
		$_limit = "15";
	}
	$_grid[TICKETGRID_LIMIT] = intval($_limit);

	// Get the current offset for this page
	if (!empty($_REQUEST["offset"]) && is_numeric($_REQUEST["offset"]))
	{
		$_offset = intval($_REQUEST["offset"]);
	} else {
		$_offset = "0";
	}

	// Is sort order changed or is it default one? First we see if there is a custom sort order passed by user
	if (!empty($_REQUEST["sortby"]))
	{
		$_grid[TICKETGRID_SORTORDER] = iif(strtolower($_REQUEST["sortorder"])=="desc", "DESC", "ASC");
		$_update["update"] = true;
		foreach ($_fieldpointer as $key=>$val)
		{
			$fieldprocess = str_replace("-", ".", cleanVar($_REQUEST["sortby"]));
			if ($val["name"] == $fieldprocess)
			{
				$_grid[TICKETGRID_SORTBY] = $fieldprocess;
				$_update["sortby"] = $key;
			}
		}
		$_update["sortorder"] = iif($_grid[TICKETGRID_SORTORDER]=="DESC", VIEW_DESC, VIEW_ASC);
	} else {
		// just use the default sort order
		$_grid[TICKETGRID_SORTBY] = $_fieldpointer[$_ticketview["sortby"]]["name"];
		if (empty($_grid[TICKETGRID_SORTBY]))
		{
			$_grid[TICKETGRID_SORTBY] = $_fieldpointer[FIELD_LASTACTIVITY]["name"];
			$_update["update"] = true;
			$_update["sortby"] = FIELD_LASTACTIVITY;
		}
		$_grid[TICKETGRID_SORTORDER] = iif($_ticketview["sortorder"]==VIEW_ASC, "ASC", "DESC");
	}

	if (!empty($ticketsearchid) && $_SWIFT["settings"]["t_searchsortdate"] == 1 && empty($_SWIFT["ticketsearch"]["ticketfilterid"]))
	{
		$_grid[TICKETGRID_SORTORDER] = "desc";
		$_grid[TICKETGRID_SORTBY] = $_fieldpointer[FIELD_LASTACTIVITY]["name"];
	}

	// Build sort statement
	$sortstatement = iif($_grid[GRID_SORTBY], " ORDER BY ". $dbCore->escape($_grid[GRID_SORTBY]) .iif(strtolower($_grid[GRID_SORTORDER])=="desc", " DESC", " ASC"));

	$fields = $_customfieldidlist = array();
	$_findex = 0;
	foreach ($_ticketview["fields"] as $key=>$val)
	{
		unset($_field);
		// Custom field or a link
		if ($val["ticketviewfieldtype"] == VIEWFIELD_CUSTOM)
		{
			$_field = array();
			$_customfieldidlist[] = $val["customfieldid"];
			$_field["name"] = "cf.".$val["customfieldid"];
			$_field["title"] = "%cf.". $val["customfieldid"] ."%";
			$_field["type"] = "custom";
			$_field["width"] = "120";
			$_field["align"] = "center";
		} else if ($val["ticketviewfieldtype"] == VIEWFIELD_LINK && isset($_fieldpointer[$val["fieldlinkid"]])) {
			$_field = $_fieldpointer[$val["fieldlinkid"]];
		} else {
			continue;
		}
		$fields[$_findex] = $_field;
		$_findex++;

		$fielddata .= '<td class="tabletitlerow" width="'.$_field["width"].'" align="'. $_field["align"] .'" nowrap>';
		if ($_grid[TICKETGRID_SORTBY] == $_field["name"])
		{
			$fielddata .= '&nbsp;<a href="'. buildURL('index.php?_m='. $_SWIFT["currentmodule"] .'&_a='.$_SWIFT["currentaction"]."&sortby=".urlencode(str_replace(".", "-", $_field["name"]))."&sortorder=".iif(strtolower($_grid[TICKETGRID_SORTORDER])=="asc", "desc", "asc").$appendurl).'" '.iif(strtolower($_grid[TICKETGRID_SORTORDER])=="asc", 'title="'. $_SWIFT["language"]["sort_desc"] .'"', 'title="'. $_SWIFT["language"]["sort_asc"] .'"').'>'. iif($_field["space"]==true, '<img src="'. $_SWIFT["themepath"] .'space.gif" border="0" />', $_field["title"]).'&nbsp;<img src="'. $_SWIFT["themepath"] .iif(strtolower($_grid[TICKETGRID_SORTORDER])=="asc", "sortasc", "sortdesc").'.gif" border="0" /></a>';
		} else if ($_field["type"] == "custom") {
			$fielddata .= '&nbsp;'.iif($_field["space"]==true, '<img src="'. $_SWIFT["themepath"] .'space.gif" border="0" />', $_field["title"]);
			$norenderoptions = true;
		} else {
			$fielddata .= '&nbsp;<a href="'. buildURL('index.php?_m='. $_SWIFT["currentmodule"] .'&_a='.$_SWIFT["currentaction"]."&sortby=".urlencode(str_replace(".", "-", $_field["name"]))."&sortorder=asc".$appendurl).'" title="'. $_SWIFT["language"]["sort_asc"] .'">'.iif($_field["space"]==true, '<img src="'. $_SWIFT["themepath"] .'space.gif" border="0" />', $_field["title"])."</a>";
		}

		unset($fieldid);
		if ($_field["name"] == "t.dateicon")
		{
			$fieldid = 'id="dateicon\'. $record[\'ticketid\'] .\'" ';
		}

		$row .= '<td '. $fieldid .'colspan="'. $_field["colspan"] .'" width="'. $_field["width"] .'" align="'. $_field["align"] .'" valign="'. $_field["valign"] .'" bgcolor="\'. $bgrecord[\''. $_field["name"] .'\'] . \'">\' . $record[\''. $_field["name"] .'\'] . \'</td>'.SWIFT_CRLF;
		$fielddata .= '</td>'.SWIFT_CRLF;
	}

	/**
	* ###############################################
	* BUILD THE QUERIES
	* ###############################################
	*/
	$_sortjoin = $sortstatement." LIMIT ". intval($_offset) .", ". intval($_limit) .";";
	$ticketcount = 0;
	$_ticketidlist = $_labelticketidlist = $ticketrank = array();
	$strdepartmentid = buildIN($departmentidlist);
	$strticketstatus = buildIN($ticketstatusidlist);
	$ojoinsql = array();
	unset($ownerjoin);
	if ($_ticketview["viewalltickets"] == 1 && $_SWIFT["staff"]["tcanviewall"] != 0)
	{
		// No Owner Join
	} else {
		if ($_ticketview["viewunassigned"] == 1 && $_SWIFT["staff"]["tcanviewall"] != 0) {
			$ojoinsql[] = "0";
		}
		if ($_ticketview["viewassigned"] == 1)
		{
			$ojoinsql[] = $_SWIFT["staff"]["staffid"];
		}
	}
	
	if (count($ojoinsql))
	{
		$ownerjoin = " AND `ownerstaffid` IN (". buildIN($ojoinsql) .")";
	}

	// ======= TICKET SEARCH TEST =======
	$usesearch = $uselabel = false;
	if ($ticketsearchid)
	{
		// Try to fetch the search contents
		$_search = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."ticketsearches` WHERE `ticketsearchid` = '". intval($ticketsearchid) ."';");
		if (!empty($_search["ticketsearchid"]) && $_search["staffid"] == $_SWIFT["staff"]["staffid"])
		{
			$searchticketidlist = unserialize($_search["ticketidlist"]);
			if (_is_array($searchticketidlist))
			{
				$usesearch = true;
				$ticketcount = count($searchticketidlist);
				$ticketrank = unserialize($_search["relevancelist"]);
				if (!_is_array($ticketrank))
				{
					$ticketrank = array();
				}
			}
		}
	} else if ($ticketlabelid) {
		$uselabel = true;
		$_labelcount = 0;
		$dbCore->query("SELECT `ticketid` FROM `". TABLE_PREFIX ."ticketlabellinks` WHERE `ticketlabelid` = '". intval($ticketlabelid) ."';");
		while ($dbCore->nextRecord())
		{
			$_labelticketidlist[] = $dbCore->Record["ticketid"];
			$_labelcount++;
		}
		$ticketcount = $_labelcount;
	}
	

	if (!$usesearch)
	{
		unset($ticketsearchid);
	}
	if (!$usesearch && !$uselabel)
	{
		// First get the total tickets that fall under our criteria.
		$_ticketcnt = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."tickets` AS t WHERE t.departmentid IN (". $strdepartmentid .") AND t.ticketstatusid IN (". $strticketstatus .")". $ownerjoin .";");
		if (empty($_ticketcnt["totalitems"]))
		{
			$ticketcount = 0;
		} else {
			$ticketcount = intval($_ticketcnt["totalitems"]);
		}
	}

	// Lets first get the total
	$_grid[TICKETGRID_TOTALITEMS] = $ticketcount;

	$name = "ticketlist";

	printFormStart($name, "index.php", "POST", false, "", "");

	if ($usesearch && empty($_SWIFT["ticketsearch"]["ticketfilterid"]))
	{
		printTableHeader(array(), "100%", "0", "0");
		echo '<tbody><tr class="row2"><td><table border="0" cellpadding="3" cellspacing="1" width="100%">'.SWIFT_CRLF;
		echo '<tr><td width="16" align="left" valign="middle"><img src="'. $_SWIFT["themepath"] .'icon_search.gif" border="0" /></td>';
		echo '<td width="300" align="left" valign="middle"><span class="smalltext">'. sprintf($_SWIFT["language"]["searchkeyw"], preg_replace('/&amp;#(x[a-f0-9]+|[0-9]+);/i', ' &#$1; ', htmlspecialchars($_search["keywords"]))) .'</span></td>';
		echo '<td align="right"><span class="smalltext">'. sprintf($_SWIFT["language"]["searchqresult"], intval($_search["resultscount"]), number_format($_search["timetaken"], 5)) .'</span></td>';
		echo '<td width="16" align="left" valign="middle"><a href="index.php?_m=tickets&_a=manage"><img src="'. $_SWIFT["themepath"] .'icon_fdelete.gif" border="0" /></a></td>';
		echo '</tr>';
		if (!empty($_search["rejectedwords"]))
		{
			echo '<tr><td colspan="4"><span class="smalltext">';
			echo sprintf($_SWIFT["language"]["rejectedwords"], $_search["rejectedwords"]);
			echo '</span></td></tr>';
		}
		echo '</table></td></tr></tbody></table><BR />'.SWIFT_CRLF;
	}

	echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">'.SWIFT_CRLF;

	$gridurl = buildURL("index.php?_m=". $_SWIFT["currentmodule"] ."&_a=". $_SWIFT["currentaction"].$appendurl);
	// ======= START PAGINATION TABLE =======

	$pagination = pagination($gridurl, $_grid[TICKETGRID_TOTALITEMS], $_limit, $_offset, "5", "pageoftotal", TRUE, FALSE, TRUE);

	echo '<tr><td><table width="100%"  border="0" cellspacing="0" cellpadding="0" id="tmenuref"><tr valign="top"><td align="left"><table border="0" cellpadding="0" cellspacing="1" class="tborder"><tr>'.$pagination.'<td class="navpageselected" nowrap><a id="tviewlink" onClick="javascript:CustomPopupRef(\'tviewmenu\', event, \'tviewlink\', \'tviewmenu\', \'tmenuref\', tviewmenuloaded);this.blur();" onMouseUp="javascript:this.blur();" href="#" title="'. $_SWIFT["language"]["views"] .'">'. $_SWIFT["language"]["views"] .'&nbsp;<img align="absmiddle" src="'. $_SWIFT["themepath"] .'menudrop.gif" border="0" /></a></td><td class="navpageselected" nowrap><a id="tlabellink" onClick="javascript:CustomPopupRef(\'tlabelmenu\', event, \'tlabellink\', \'tlabelmenu\', \'tmenuref\', tlabelmenuloaded);this.blur();" onMouseUp="javascript:this.blur();" href="#" title="'. $_SWIFT["language"]["labels"] .'">'. $_SWIFT["language"]["labels"] .'&nbsp;<img align="absmiddle" src="'. $_SWIFT["themepath"] .'menudrop.gif" border="0" /></a></td><td class="navpageselected" nowrap><a onClick="javascript:switchDisplay(\'trmassaction\');" href="#" title="'. $_SWIFT["language"]["massaction"] .'">'. $_SWIFT["language"]["massaction"] .'</a></td></tr></table></td>' . '<td width="100%" align="right" valign="middle" width="1"><input type="text" name="s_query" class="quicksearch" value="'. $_REQUEST["s_query"] .'" /></td><td width="1"><img src="'. $_SWIFT["themepath"] .'space.gif" width="4" height="1" /></td>'.'<td width="100%" align="right" valign="middle" width="1"><select name="searchfield" class="quicksearch">
  <option value="ticketid"'. iif($_REQUEST["searchfield"]=="ticketid", " selected") .'>'. $_SWIFT["language"]["s_ticketid"] .'</option>
  <option value="fullname"'. iif($_REQUEST["searchfield"]=="fullname", " selected") .'>'. $_SWIFT["language"]["s_fullname"] .'</option>
  <option value="lastreplier"'. iif($_REQUEST["searchfield"]=="lastreplier", " selected") .'>'. $_SWIFT["language"]["s_lastreplier"] .'</option>
  <option value="contents"'. iif(empty($_REQUEST["searchfield"])||$_REQUEST["searchfield"]=="contents", " selected") .'>'. $_SWIFT["language"]["s_messages"] .'</option>
  <option value="subject"'. iif($_REQUEST["searchfield"]=="subject", " selected") .'>'. $_SWIFT["language"]["s_subject"] .'</option>
</select></td><td width="1"><img src="'. $_SWIFT["themepath"] .'space.gif" width="4" height="1" /></td>'.'<td align="right" width="1"><table border="0" cellpadding="0" cellspacing="1" class="tborder"><tr>'. '<td class="navpageselected" nowrap><a href="javascript:document.ticketlist.submit();" title="'. $_SWIFT["language"]["quicksearch"] .'">'. $_SWIFT["language"]["quicksearch"] .'</a></td>'.'<td class="navpageselected" nowrap><a onclick="javascript:displayGridTabData(\''. $name .'\', false);hideTabOn(\'gridopt'.$name.'\', \'settings\');" href="#" title="'. $_SWIFT["language"]["options"] .'">'. $_SWIFT["language"]["options"] .'</a></td></tr></table></td></tr></table></tr></td>'.SWIFT_CRLF;
	echo '<tr><td><img src="'. $_SWIFT["themepath"] .'space.gif" width="1" height="6" /></td></tr>'.SWIFT_CRLF;
	// ======= END PAGINATION TABLE =======

	echo '<tr><td>'.SWIFT_CRLF;


	$totalfields = count($fields)+1;
	$colspan = $totalfields;

	// ======= START GRID HEADER =======

	// ======= OPTIONS TABS =======
	echo '<table cellspacing="0" cellpadding="0" border="0" width="100%" style="border-collapse: collapse;width: 100%; height: 100%;DISPLAY: none;" id="gridtableopt'. $name .'"><tr style="height: 1em"><td align="left"><div id="gridopt'. $name .'"><ul id="tab"><li><a href="#" class="currenttab" onClick="this.blur(); return switchGridTab(\'settings\', \'gridoptions\');" id="settings" title="'. $_SWIFT["language"]["settings"] .'">'. $_SWIFT["language"]["settings"] .'</a></li></ul></div></td></tr>'.SWIFT_CRLF;

	// ======= SETTINGS =======
	echo '<tr style="height: 1em"><td align="left"><div id="tab_settings" style="DISPLAY: none;" class="tabcontent"><table border="0" cellpadding="3" cellspacing="1" class="tborder" width="100%">'.SWIFT_CRLF;

	$_POST["autorefresh"] = $_gridset["autorefresh"];
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["arnoref"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$options[1]["title"] = $_SWIFT["language"]["ar30sec"];
	$options[1]["value"] = "30";
	$options[2]["title"] = $_SWIFT["language"]["ar1min"];
	$options[2]["value"] = "60";
	$options[3]["title"] = $_SWIFT["language"]["ar5min"];
	$options[3]["value"] = "300";
	$options[4]["title"] = $_SWIFT["language"]["ar15min"];
	$options[4]["value"] = "900";
	$options[5]["title"] = $_SWIFT["language"]["ar30min"];
	$options[5]["value"] = "1800";
	$options[6]["title"] = $_SWIFT["language"]["ar1hr"];
	$options[6]["value"] = "3600";
	printSelectRow("autorefresh", $_SWIFT["language"]["gautorefresh"], $_SWIFT["language"]["desc_gautorefresh"], $options);

	$_POST["opennewwindow"] = $_gridset["opennewwindow"];
	printYesNoRow("opennewwindow", $_SWIFT["language"]["gopenewwin"], $_SWIFT["language"]["desc_gopenewwin"], iif($_gridset["opennewwin"]==1, true,false));

	printDescRow($_SWIFT["language"]["postreplyoptions"]);
	$_POST["replynav"] = $_gridset["replynav"];
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["rnticketlist"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$options[1]["title"] = $_SWIFT["language"]["rnticket"];
	$options[1]["value"] = "1";
	$options[2]["title"] = $_SWIFT["language"]["rnnextticket"];
	$options[2]["value"] = "2";
	printSelectRow("replynav", $_SWIFT["language"]["replynav"], $_SWIFT["language"]["desc_replynav"], $options);

	$options = array();
	$_POST["rnticketstatusid"] = $_gridset["rnticketstatusid"];
	$index = 1;
	$options[0]["title"] = $_SWIFT["language"]["unspecified"];
	$options[0]["value"] = 0;
	$options[0]["selected"] = true;
	foreach ($_SWIFT["statuscache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["ticketstatusid"];
		$index++;
	}
	printSelectRow("rnticketstatusid", $_SWIFT["language"]["rnticketstatus"], $_SWIFT["language"]["desc_rnticketstatus"], $options);

	$_POST["rnsetowner"] = $_gridset["rnsetowner"];
	printYesNoRow("rnsetowner", $_SWIFT["language"]["rnsetowner"], $_SWIFT["language"]["desc_rnsetowner"], iif($_gridset["rnsetowner"]==1, true,false));


	printSubmitRow($_SWIFT["language"]["update"]);
	echo '</table><BR /> </div></td></tr></table>';

	printMainTableHeader(sprintf($_SWIFT["language"]["ticketslist"], htmlspecialchars($_ticketview["title"])), "100%", "0", "0", "float: left; position: relative;");

	// ======= TOOLBAR OPTIONS =======

	if (count($options["toolbar"]))
	{
		echo '<tr>'.SWIFT_CRLF;
		echo '<td class="toolbarrow" align="left" colspan="'. $colspan .'" valign="middle" nowrap><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="5"><img src="'. $_SWIFT["themepath"] .'grip.gif" border="0" /></td><td class="toolbarrow"><span class="toolbartext">&nbsp;';
			
		for ($ii=0; $ii<count($options["toolbar"]); $ii++)
		{
			echo '<a href="'. $options["toolbar"][$ii]["url"] .'" id="white" title="'. $options["toolbar"][$ii]["title"] .'">'. $options["toolbar"][$ii]["title"] .'</a>';
			if ($ii != (count($options["toolbar"])-1))
			{
				echo " | ";
			}
		}

		echo '</span></td></tr></table></td>'.SWIFT_CRLF;
		echo '</tr>'.SWIFT_CRLF;
	}
	// ======= TOOLBAR OPTIONS =======

	echo '<tr>'.SWIFT_CRLF;
	echo '<td class="tabletitlerow" align="center" valign="middle" width=20 nowrap><input type="checkbox" name="allselect" class="swiftcheckbox" onClick="javascript:toggleAll(document.'.$name.');displayObject(\'trmassaction\');"></td>'.SWIFT_CRLF;


	if (count($_customfieldidlist))
	{
		$joincflist = buildIN($_customfieldidlist);
		$replacearray = $replacewith = array();
		$dbCore->query("SELECT `customfieldid`, `title` FROM `". TABLE_PREFIX ."customfields` WHERE `customfieldid` IN (". $joincflist .");");
		while ($dbCore->nextRecord())
		{
			$replacearray[] = "%cf.".  intval($dbCore->Record["customfieldid"])."%";
			$replacewith[] = $dbCore->Record["title"];
		}

		$fielddata = str_replace($replacearray, $replacewith, $fielddata);
	}
	echo $fielddata;
	unset($fielddata);

	if ($usesearch && empty($_SWIFT["ticketsearch"]["ticketfilterid"]))
	{
		echo '<td class="tabletitlerow" align="center" valign="middle" width=20 nowrap><img src="'. $_SWIFT["themepath"] .'icon_searchlookup.gif" align="absmiddle" border="0" /></td>'.SWIFT_CRLF;
	}

	echo '</tr>'.SWIFT_CRLF;
	// ======= END GRID HEADER =======


	// ======= START GRID CONTENTS =======
	// Fetch the required data now
	if ($usesearch == true)
	{
		$_ticketidlist = &$searchticketidlist;
	} else if ($uselabel == true) {
		$_ticketidlist = &$_labelticketidlist;
	} else {
		$dbCore->query("SELECT t.ticketid FROM `". TABLE_PREFIX ."tickets` AS t WHERE t.departmentid IN (". $strdepartmentid .") AND t.ticketstatusid IN (". $strticketstatus .")". $ownerjoin ." ". $_sortjoin .";");
		while ($dbCore->nextRecord())
		{
			$_ticketidlist[] = $dbCore->Record["ticketid"];
		}
	}

	$strticketid = buildIN($_ticketidlist);
	$_customfieldvalues = array();
	if (count($_customfieldidlist))
	{
		$dbCore->query("SELECT `customfieldid`, `typeid`, `fieldvalue` FROM `". TABLE_PREFIX ."customfieldvalues` WHERE `customfieldid` IN (". $joincflist .") AND `typeid` IN (". $strticketid .");");
		while ($dbCore->nextRecord())
		{
			$_customfieldvalues[$dbCore->Record["typeid"]][$dbCore->Record["customfieldid"]] = $dbCore->Record["fieldvalue"];
		}
	}

	if ($_SWIFT["settings"]["t_tpreview"] == 1)
	{
		$_tquery = "SELECT t.*, tl.lockdateline, tl.lockstaffid, tp.contents AS preview FROM `". TABLE_PREFIX ."tickets` AS t LEFT JOIN `". TABLE_PREFIX ."ticketlocks` AS tl ON (t.ticketid = tl.ticketid) LEFT JOIN `". TABLE_PREFIX ."ticketposts` AS tp ON (tp.ticketpostid = t.lastpostid) WHERE t.ticketid IN (". $strticketid .") ". iif($usesearch==true, $_sortjoin, $sortstatement).";";
	} else {
		$_tquery = "SELECT t.*, tl.lockdateline, tl.lockstaffid FROM `". TABLE_PREFIX ."tickets` AS t LEFT JOIN `". TABLE_PREFIX ."ticketlocks` AS tl ON (t.ticketid = tl.ticketid) WHERE t.ticketid IN (". $strticketid .") ". iif($usesearch==true, $_sortjoin, $sortstatement).";";
	}

	$flagbgcolors = array(FLAG_PURPLE => "#A5587C", FLAG_ORANGE => "#FF8C5A", FLAG_GREEN => "#8BB467", FLAG_YELLOW => "#FFC160", FLAG_RED => "#CF5D60", FLAG_BLUE => "#5C83B4");
	$flagicons = array(FLAG_PURPLE => "icon_purpleflag.gif", FLAG_ORANGE => "icon_orangeflag.gif", FLAG_GREEN => "icon_greenflag.gif", FLAG_YELLOW => "icon_yellowflag.gif", FLAG_RED => "icon_redflag.gif", FLAG_BLUE => "icon_blueflag.gif");

	$dbCore->query($_tquery, 2);
	$cnt = 0;
	while ($dbCore->nextRecord(2))
	{
		unset($record);
		unset($bgrecord);
		$cnt++;
		$rowbg = getRowBG();
		$id = $dbCore->Record2["ticketid"];
		$record = $dbCore->Record2;

		if (!empty($_SWIFT["prioritycache"][$record["priorityid"]]["bgcolorcode"]))
		{
			$trbgcolor = $_SWIFT["prioritycache"][$record["priorityid"]]["bgcolorcode"];
		} else {
			unset($trbgcolor);
		}

		if ($record["hasnotes"] == 1)
		{
			$rowbg = "rownotes";
		}
		$record["overdue"] = false;
		if ($record["duetime"] != 0)
		{
			if (DATENOW >= $record["duetime"])
			{
				// Overdue
				$record["t.duetime"] = '<span class=\'tickettextred\'>'.$_SWIFT["language"]["overdue"].'</span>';
				$record["overdue"] = true;
			} else {
				$record["t.duetime"] = strColorDate(($record["duetime"]-DATENOW), true);
			}
		}

		if ($record["laststaffreplytime"] != 0)
		{
			$record["t.laststaffreplytime"] = strColorDate((DATENOW-$record["laststaffreplytime"]), false);
		} else {
			$record["t.laststaffreplytime"] = '<span class=\'tickettextred\'>'.$_SWIFT["language"]["snoreply"].'</span>';
		}

		if ($record["overdue"] == true)
		{
			$trbgcolor = $_SWIFT["settings"]["t_overduecolor"];
		}

		$_lockthreshold = DATENOW-$_SWIFT["settings"]["t_locktimeout"];
		// Is ticket locked?
		if (!empty($record["lockstaffid"]) && $record["lockdateline"] > $_lockthreshold && $record["lockstaffid"] != $_SWIFT["staff"]["staffid"])
		{
			$record["islocked"] = true;
		}

		echo '<tr id="trid'. $id .'" style="BACKGROUND-COLOR:'. $trbgcolor .';" class="'. $rowbg .'" onmouseover="'. "showHighlight(this);" .'" onmouseout="'. "clearHighlight(this, '$rowbg', '$trbgcolor');" .'" onclick="'. "if (document.{$name}.itemhighlight{$id}.value == '1') { this.className = 'rowselect';} else { this.className = '$rowbg';}" .'">'.SWIFT_CRLF;
		echo '<td align="center" valign="middle">'. "<input type='checkbox' name='itemid[]' value='$id' class=\"swiftcheckbox\" onclick=\"if (document.{$name}.itemhighlight{$id}.value == '0') {document.{$name}.itemhighlight{$id}.value = '1';} else {document.{$name}.itemhighlight{$id}.value = '0';  }displayObject('trmassaction');\"><input type='hidden' name='itemhighlight{$id}' value='0'>" .'</td>'.SWIFT_CRLF;

		// We replace all instances of field names in [] braces with their respective values, *much* faster (trust me) than doing a for loop for fields inside another while loop ;)
		$ticketurl = "index.php?_m=tickets&_a=viewticket&ticketid=". intval($record["ticketid"]).iif(!empty($_search["keywords"]), "&highlight=".urlencode($_search["keywords"])) .iif(!empty($_REQUEST["departmentid"]), "&departmentid=". intval($_REQUEST["departmentid"])) .iif(!empty($_REQUEST["ticketstatusid"]), "&ticketstatusid=". intval($_REQUEST["ticketstatusid"])) .iif(!empty($_REQUEST["ticketsearchid"]), "&ticketsearchid=".intval($_REQUEST["ticketsearchid"])).iif(!empty($_REQUEST["ticketlabelid"]), "&ticketlabelid=".intval($_REQUEST["ticketlabelid"]));
		$record["t.ticketid"] = "<a href='". $ticketurl ."' target='". iif($_gridset["opennewwindow"]==1, "_blank", "") ."'>".iif($_SWIFT["settings"]["t_eticketid"]=="seq", intval($record["ticketid"]), $record["ticketmaskid"]).'</a>';

		$record["t.subject"] = '<div><span style="float:right;">'. iif($record["islabeled"]==1, '<img src="'. $_SWIFT["themepath"] .'islabeled.gif" border="0" /> '). iif($record["ownerstaffid"]==$_SWIFT["staff"]["staffid"], '<img src="'. $_SWIFT["themepath"] .'icon_ownedticket.gif" border="0" /> '). iif($record["isescalated"]==1, '<img src="'. $_SWIFT["themepath"] .'isescalated.gif" border="0" /> '). iif($record["islocked"]==1, '<img src="'. $_SWIFT["themepath"] .'icon_lock.gif" border="0" /> ') .'</span><a href=\''. $ticketurl .'\' target=\''. iif($_gridset["opennewwindow"]==1, "_blank", "") .'\'><img src=\''. $_SWIFT["themepath"]. 'icon_ticketnotselfreplied.gif\' border=\'0\' align=\'absmiddle\' />'. iif($record["hasattachments"]==1,'&nbsp;<img src=\''. $_SWIFT["themepath"]. 'icon_paperclip.gif\' border=\'0\' align=\'absmiddle\' />') .'&nbsp;'.htmlspecialchars($record["subject"]).'</a>'.iif($_SWIFT["settings"]["t_enpagin"]==1, smallPagination("?_m=tickets&_a=viewticket&ticketid=".$record["ticketid"], ($record["totalreplies"]+1), intval($_SWIFT["settings"]["t_postlimit"]), -1, TRUE)).'</div>';

		$record["t.emailqueueid"] = htmlspecialchars(stripName($_SWIFT["queuecache"]["list"][$record["emailqueueid"]]["email"], 15));
		$record["t.departmentid"] = htmlspecialchars(stripName($_SWIFT["departmentcache"][$record["departmentid"]]["title"], 13));
		$record["t.ticketstatusid"] = '<font color=\''. $_SWIFT["statuscache"][$record["ticketstatusid"]]["statuscolor"] .'\'>'.htmlspecialchars($_SWIFT["statuscache"][$record["ticketstatusid"]]["title"]).'</font>';
		$record["t.dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["dateline"]);
		$record["t.ownerstaffid"] = iif(!empty($record["ownerstaffid"]), htmlspecialchars(stripName($_SWIFT["staffcache"][$record["ownerstaffid"]]["fullname"], 15)), $_SWIFT["language"]["unassigned"]);
		$record["t.priorityid"] = '<font color=\''. $_SWIFT["prioritycache"][$record["priorityid"]]["frcolorcode"] .'\'>'.htmlspecialchars($_SWIFT["prioritycache"][$record["priorityid"]]["title"]).'</font>';
		$record["t.lastreplier"] = htmlspecialchars(stripName(iif(empty($record["lastreplier"]), $record["fullname"], $record["lastreplier"]), 15));
		$record["t.fullname"] = htmlspecialchars(stripName($record["fullname"], 15));
		$record["t.timeworked"] = number_format($record["timeworked"]/60);
		$record["t.email"] = htmlspecialchars(stripName($record["email"], 20));
		$record["t.totalreplies"] = intval($record["totalreplies"]);
		$record["t.tgroupid"] = htmlspecialchars($_SWIFT["tgroupcache"][$record["tgroupid"]]["title"]);
		$record["t.lastactivity"] = strColorDate((DATENOW-$record["lastactivity"]));
		$record["t.assignstatus"] = iif(!empty($record["ownerstaffid"]), '<img src=\''. $_SWIFT["themepath"] .'icon_greenarrow.gif\' border=\'0\' align=\'absmiddle\' />&nbsp;'.$_SWIFT["language"]["tassigned"], '<img src=\''. $_SWIFT["themepath"] .'icon_grayarrow.gif\' border=\'0\' align=\'absmiddle\' />&nbsp;'.$_SWIFT["language"]["tunassigned"]);

		if ($_SWIFT["staff"]["tcanviewall"] != 1 && $record["ownerstaffid"] != $_SWIFT["staff"]["staffid"])
		{
			// do nothing...
		} else {
			if ($record["lastactivity"] > $_SWIFT["staff"]["lastvisit"])
			{
				// New Ticket
				$record["t.dateicon"] = '<img src=\''. $_SWIFT["themepath"]. iif($record["isphonecall"]=="1", "icon_ticketphone.gif", 'icon_ticketyellow.gif') .'\' border="0" />';
				$bgrecord["t.dateicon"] = '#FFF8E9';
			} else {
				// Normal Ticket
				$record["t.dateicon"] = '<img src=\''. $_SWIFT["themepath"]. iif($record["isphonecall"]=="1", "icon_ticketphone.gif", 'icon_ticket.gif') .'\' border="0" />';
			}
		}
		$record["t.flagtype"] = iif(!empty($record["flagtype"]), '<img src=\''. $_SWIFT["themepath"]. $flagicons[$record["flagtype"]] .'\' border=\'0\' />', '<img src=\''. $_SWIFT["themepath"] .'icon_flagblank.gif\' width=\'18\' height=\'20\' border=\'0\' />');

		if ($record["hasnotes"] == 1 && $record["hasbilling"] == 1)
		{
			$noteimage = "icon_ticketnotebilling.gif";
		} else if ($record["hasnotes"] == 1) {
			$noteimage = "icon_ticketnote.gif";
		} else if ($record["hasbilling"] == 1) {
			$noteimage = "icon_timetrack.gif";
		} else {
			$noteimage = "space.gif";
		}

		$record["t.hasnotes"] ='<img src=\''. $_SWIFT["themepath"]. $noteimage.'\' border=\'0\' />';

		$bgrecord["t.flagtype"] = $flagbgcolors[$record["flagtype"]];

		$tooltip = $_SWIFT["language"]["f_ticketid"].": ".$record["t.ticketid"]."<BR />". $_SWIFT["language"]["f_subject"].": ".htmlspecialchars($record["subject"])."<BR />". $_SWIFT["language"]["f_queue"].": ".$record["t.emailqueueid"]."<BR />". $_SWIFT["language"]["f_department"].": ".$record["t.departmentid"]."<BR />". $_SWIFT["language"]["f_ticketstatus"].": ".$record["t.ticketstatusid"]."<BR />". $_SWIFT["language"]["f_date"].": ".$record["t.dateline"]."<BR />". $_SWIFT["language"]["f_owner"].": ".$record["t.ownerstaffid"]."<BR />". $_SWIFT["language"]["f_priority"].": ".$record["t.priorityid"]."<BR />". $_SWIFT["language"]["f_lastreplier"].": ".htmlspecialchars($record["lastreplier"])."<BR />". $_SWIFT["language"]["f_fullname"].": ".htmlspecialchars($record["fullname"])."<BR />". $_SWIFT["language"]["f_timeworked"].": ".$record["t.timeworked"]."<BR />". $_SWIFT["language"]["f_email"].": ".htmlspecialchars($record["email"])."<BR />". $_SWIFT["language"]["f_totalreplies"].": ".$record["t.totalreplies"]."<BR />". $_SWIFT["language"]["f_lastactivity"].": ".$record["t.lastactivity"]."<BR />". $_SWIFT["language"]["f_duedate"].": ".$record["t.duetime"]."<BR />".iif(!empty($record["preview"]), "<HR />".htmlspecialchars(preg_replace("#(\r\n|\r|\n)#s", "<BR />", $record["preview"])));

		$record["t.dateicon"] = '<a id="ldateicon'. intval($record["ticketid"]) .'" href="index.php?_m=tickets&_a=viewticket&ticketid='. intval($record["ticketid"]) .'" onmouseover="javascript:CustomOver(\''. addslashes($tooltip) .'\', \'ldateicon'. intval($record["ticketid"]) .'\', \'dateicon'. intval($record["ticketid"]) .'\');" onmouseout="return nd();">'.  $record["t.dateicon"].'</a>';

		if (count($_customfieldvalues))
		{
			$cfdata = &$_customfieldvalues[$record["ticketid"]];
			foreach ($cfdata as $key=>$val)
			{
				$record["cf.".$key] = stripName(htmlspecialchars($val), 30);
			}
		}

		eval("echo '".$row."';");

		if ($usesearch && empty($_SWIFT["ticketsearch"]["ticketfilterid"]))
		{
			$_relevance = intval($ticketrank[$id]);
			if (empty($_relevance))
			{
				$_relevance = "-";
			}
			if ($_relevance > 80 && $_relevance <= 100)
			{
				$_colorcode = "#D6383C";
			} else if ($_relevance > 60 && $_relevance <= 80) {
				$_colorcode = "#FF8C5A";
			} else if ($_relevance > 30 && $_relevance <= 60) {
				$_colorcode = "#5A96E0";
			} else if ($_relevance > 10 && $_relevance <= 30) {
				$_colorcode = "#FFC160";
			} else {
				$_colorcode = "#EECF9E";
			}

			echo '<td bgcolor="'. $_colorcode .'" align="center"><font color="#FFFFFF">'. $_relevance .'</font></td>';
		}
		echo '</tr>'.SWIFT_CRLF;
	}

	// ======= MASS ACTION STUFF =======
	// Ticket Status Options
	$statusoptions = $priorityoptions = $departmentoptions = "";
	foreach ($_SWIFT["statuscache"] as $key=>$val)
	{
		$statusoptions .= '<option value="'. $val["ticketstatusid"] .'" style="color:'. $val["statuscolor"] .'">'. htmlspecialchars($val["title"]) .'</option>';
	}
	
	// Ticket Priorities
	foreach ($_SWIFT["prioritycache"] as $key=>$val)
	{
		$priorityoptions .= '<option value="'. $val["priorityid"] .'" style="background:'. $val["bgcolorcode"] .';color:'. $val["frcolorcode"] .'">'. htmlspecialchars($val["title"]) .'</option>';
	}
	
	// Departments
	foreach ($_SWIFT["departmentcache"] as $key=>$val)
	{
		if ($val["departmentmodule"] == MODULE_TICKETS)
		{
			$departmentoptions .= '<option value="'. $val["departmentid"] .'">'. htmlspecialchars($val["title"]) .'</option>';
		}
	}
	
	// Ticket Owners
	$owneroptions .= '<option value="0">'. $_SWIFT["language"]["unassigned"] .'</option>';
	foreach ($_SWIFT["staffcache"] as $key=>$val)
	{
		$owneroptions .= '<option value="'. $val["staffid"] .'">'. htmlspecialchars($val["fullname"]) .'</option>';
	}

	echo '<tr id="trmassaction" style="display: none;">'.SWIFT_CRLF;
	echo '<td class="'. getRowBG() .'" align="center" valign="middle" colspan="'. $colspan .'" nowrap>
	<select name="ma_options" class="gridmassaction">
	<option value="0" selected>'. $_SWIFT["language"]["maoptions"] .'</option>';

	if ($_SWIFT["staff"]["tdeleteticket"] != 0)
	{
		echo '	<option value="delete">'. $_SWIFT["language"]["delete"] .'</option>';
	}
	if ($_SWIFT["staff"]["tbandelete"] != 0)
	{
		echo '<option value="bandelete">'. $_SWIFT["language"]["bandelete"] .'</option>';
	}

	if($_SWIFT["staff"]["tmerge"] != 0)
	{
	echo '<option value="mergetickets">'. $_SWIFT["language"]["mergetickets"] .'</option>';
	}

	echo '<option value="markasdue">'. $_SWIFT["language"]["markasdue"] .'</option>
	<option value="markduein24">'. $_SWIFT["language"]["markduein24hrs"] .'</option>
	<option value="print">'. $_SWIFT["language"]["maprint"] .'</option>
	<option value="reply">'. $_SWIFT["language"]["massreply"] .'</option>
	</select> + 
	<select name="ma_staffid" class="gridmassaction">
	<option value="" selected>'. $_SWIFT["language"]["maowner"] .'</option>
	'. $owneroptions .'
	</select> + 
	<select name="ma_departmentid" class="gridmassaction">
	<option value="0" selected>'. $_SWIFT["language"]["madepartments"] .'</option>
	'. $departmentoptions .'
	</select> + 
	<select name="ma_ticketstatusid" class="gridmassaction">
	<option value="0" selected>'. $_SWIFT["language"]["maticketstatus"] .'</option>
	'. $statusoptions .'
	</select> + 
	<select name="ma_priorityid" class="gridmassaction">
	<option value="0" selected>'. $_SWIFT["language"]["maticketpriority"] .'</option>
	'. $priorityoptions .'
	</select> + 
	<select name="ma_flagtype" class="swiftselect">
	<option value="" selected>'. addslashes($_SWIFT["language"]["nolabel"]) .'</option>';

	foreach ($_SWIFT["ticketlabelcache"] as $key=>$val)
	{
		if ($val["labeltype"] == SWIFTPUBLIC || ($val["labeltype"] == SWIFTPRIVATE && $val["staffid"] == intval($_SWIFT["staff"]["staffid"])))
		{
			echo '<option value="l_'. intval($val["ticketlabelid"]) .'" style="background: #FFC160; color: #FFFFFF;">'. htmlspecialchars($val["title"]) .'</option>';
		}
	}

	echo '<option value="">'. addslashes($_SWIFT["language"]["noflag"]) .'</option>
	<option value="f_'. FLAG_PURPLE .'" style="background: '. $flagbgcolors[FLAG_PURPLE] .'; color: #FFFFFF;">'. addslashes($_SWIFT["language"]["purpleflag"]) .'</option>
	<option value="f_'. FLAG_RED .'" style="background: '. $flagbgcolors[FLAG_RED] .'; color: #FFFFFF;">'. addslashes($_SWIFT["language"]["redflag"]) .'</option>
	<option value="f_'. FLAG_ORANGE .'" style="background: '. $flagbgcolors[FLAG_ORANGE] .'; color: #FFFFFF;">'. addslashes($_SWIFT["language"]["orangeflag"]) .'</option>
	<option value="f_'. FLAG_YELLOW .'" style="background: '. $flagbgcolors[FLAG_YELLOW] .'; color: #FFFFFF;">'. addslashes($_SWIFT["language"]["yellowflag"]) .'</option>
	<option value="f_'. FLAG_BLUE .'" style="background: '. $flagbgcolors[FLAG_BLUE] .'; color: #FFFFFF;">'. addslashes($_SWIFT["language"]["blueflag"]) .'</option>
	<option value="f_'. FLAG_GREEN .'" style="background: '. $flagbgcolors[FLAG_GREEN] .'; color: #FFFFFF;">'. addslashes($_SWIFT["language"]["greenflag"]) .'</option>
	<option value="f_0" style="BACKGROUND: #CCCCCC; COLOR: #FFFFFF;">'. $_SWIFT["language"]["clearflag"] .'</option>
	</select>
	<input type="submit" name="submitbtn" value="'. $_SWIFT["language"]["go"] .'" class="swiftmabutton">
	</td>'.SWIFT_CRLF;
	echo '</tr>'.SWIFT_CRLF;


	printMainTableFooter();

	// ======= START SECOND PAGINATION TABLE =======
	echo '<tr><td><img src="'. $_SWIFT["themepath"] .'space.gif" width="1" height="6" /></tr></td>'.SWIFT_CRLF;
	echo '<tr><td><table width="100%"  border="0" cellspacing="0" cellpadding="0"><tr valign="top"><td align="left"><table border="0" cellpadding="0" cellspacing="1" class="tborder"><tr>'.$pagination.'</tr></table></td></tr></table></tr></td>'.SWIFT_CRLF;
	// ======= END SECOND PAGINATION TABLE =======

	echo '</tr></td></table>'.SWIFT_CRLF;
	// ======= END GRID CONTENTS =======

	addHiddenField("_m", $_SWIFT["currentmodule"]);
	addHiddenField("_a", $_SWIFT["currentaction"]);
	addHiddenField("departmentid", intval($_REQUEST["departmentid"]));
	addHiddenField("ticketstatusid", intval($_REQUEST["ticketstatusid"]));
	addHiddenField("ticketsearchid", intval($_REQUEST["ticketsearchid"]));
	printFormEnd();

	if ($_update["update"] == true)
	{
		updateViewOrder($_ticketview["ticketviewid"], $_update["sortby"], $_update["sortorder"]);
	}
	if ($gridsetupdate == true)
	{
		$datastore->update("ticketgridcache", $_SWIFT["ticketgridcache"]);
	}

	$gridoutput = ob_get_contents();
	ob_end_clean();

	echo $gridoutput;
}

/**
* Update the View Order
*/
function updateViewOrder($ticketviewid, $sortby = "", $sortorder = "")
{
	global $dbCore;

	require_once ("./modules/tickets/functions_views.php");
	$_sql = array();
	if (!empty($sortby))
	{
		$_sql[] = "`sortby` = '". intval($sortby) ."'";
	}
	if (!empty($sortorder))
	{
		$_sql[] = "`sortorder` = '". intval($sortorder) ."'";
	}

	if (count($_sql))
	{
		$dbCore->query("UPDATE `". TABLE_PREFIX ."ticketviews` SET ". implode(",",$_sql) ." WHERE `ticketviewid` = '". intval($ticketviewid) ."';");

		rebuildTicketViewsCache();
	}
}

/**
* Strip X number of chars and add ... at end
*/
function stripName($string, $length)
{
	if (strlen($string) > $length)
	{
		$string = substr($string,0, $length)."...";
	}

	return $string;
}

/**
* Gets the list of displayable ticket status ids
*/
function getDisplayTicketStatusList($showall = false)
{
	global $_SWIFT;

	$_ticketstatus = array();
	foreach ($_SWIFT["statuscache"] as $key=>$val)
	{
		if ($val["displayinmainlist"] == 1 || $showall == true)
		{
			$_ticketstatus[] = $val["ticketstatusid"];
		}
	}

	return $_ticketstatus;
}

/**
* Get the ticket views for this staff
*/
function getStaffTicketViews($staffid)
{
	global $_SWIFT;

	if (isset($_SWIFT["ticketviews"][$staffid]))
	{
		return $_SWIFT["ticketviews"][$staffid];
	}

	$_ticketviews = array();
	foreach ($_SWIFT["ticketviewcache"] as $key=>$val)
	{
		if (($val["viewtype"] == VIEW_PUBLIC) || ($val["viewtype"] == VIEW_PRIVATE && $val["staffid"] == $staffid))
		{
			$_ticketviews[$val["ticketviewid"]] = $val;
		}
	}

	$_SWIFT["ticketviews"][$staffid] = $_ticketviews;

	return $_ticketviews;
}

/**
* Gets the User Ticket history
*/
function getUserHistory($userid)
{
	global $dbCore;

	if (empty($userid))
	{
		return false;
	}

	$_tickets = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."tickets` WHERE `userid` = '". intval($userid) ."' ORDER BY `dateline` ASC;");
	while ($dbCore->nextRecord())
	{
		$_tickets[$dbCore->Record["ticketid"]] = $dbCore->Record;
	}

	return $_tickets;
}

/**
* Gets the User Ticket history from Emails
*/
function getUserHistoryEmail($emaillist)
{
	global $dbCore;

	if (!_is_array($emaillist))
	{
		return false;
	}

	$_tickets = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."tickets` WHERE `email` IN (". buildIN($emaillist) .") ORDER BY `dateline` ASC;");
	while ($dbCore->nextRecord())
	{
		$_tickets[$dbCore->Record["ticketid"]] = $dbCore->Record;
	}

	return $_tickets;
}

/**
* Returns the View Count based on ticketviewid, departmentid, ticketstatusid
*/
function customViewProcess($ticketviewid, $departmentidlist, $ticketstatusidlist, $type)
{
	global $dbCore, $_SWIFT, $_fieldpointer;

	$_ticketview = &$_SWIFT["ticketviewcache"][$ticketviewid];
	if (!is_array($_ticketview))
	{
		trigger_error($_SWIFT["language"]["invalidview"], E_USER_ERROR);
	}

	$_grid = $_update = array();
	$_staffid = &$_SWIFT["staff"]["staffid"];

	// Get the current offset for this page
	if (!empty($_REQUEST["offset"]) && is_numeric($_REQUEST["offset"]))
	{
		$_offset = intval($_REQUEST["offset"]);
	} else {
		$_offset = "0";
	}

	$_limit = $_ticketview["ticketsperpage"];
	if (!$_limit)
	{
		$_limit = "15";
	}

	$_sortby = $_fieldpointer[$_ticketview["sortby"]]["name"];
	if (empty($_sortby))
	{
		$_sortby = $_fieldpointer[FIELD_LASTACTIVITY]["name"];
	}
	$_sortorder = iif($_ticketview["sortorder"]==VIEW_ASC, "ASC", "DESC");

	// Build sort statement
	$sortstatement = iif($_sortby, " ORDER BY ". $dbCore->escape($_sortby) .iif(strtolower($_sortorder)=="desc", " DESC", " ASC"));

	$_sortjoin = $sortstatement." LIMIT ". intval($_offset) .", ". intval($_limit) .";";

	$ticketcount = 0;
	$_ticketidlist = array();
	$strdepartmentid = buildIN($departmentidlist);
	$strticketstatus = buildIN($ticketstatusidlist);
	$ojoinsql = array();
	unset($ownerjoin);
	if ($_ticketview["viewalltickets"] == 1)
	{
		// No Owner Join
	} else {
		if ($_ticketview["viewunassigned"] == 1) {
			$ojoinsql[] = "0";
		}
		if ($_ticketview["viewassigned"] == 1)
		{
			$ojoinsql[] = $_SWIFT["staff"]["staffid"];
		}
	}
	
	if (count($ojoinsql))
	{
		$ownerjoin = " AND `ownerstaffid` IN (". buildIN($ojoinsql) .")";
	}

	if ($type == CUSTOMVIEW_COUNT)
	{
		$_ticketcnt = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."tickets` AS t WHERE t.departmentid IN (". $strdepartmentid .") AND t.ticketstatusid IN (". $strticketstatus .")". $ownerjoin .";");
		if (empty($_ticketcnt["totalitems"]))
		{
			$ticketcount = 0;
		} else {
			$ticketcount = intval($_ticketcnt["totalitems"]);
		}
		return $ticketcount;
	} else if ($type == CUSTOMVIEW_FETCH) {
		$dbCore->query("SELECT t.ticketid FROM `". TABLE_PREFIX ."tickets` AS t WHERE t.departmentid IN (". $strdepartmentid .") AND t.ticketstatusid IN (". $strticketstatus .")". $ownerjoin ." ". $_sortjoin .";");
		while ($dbCore->nextRecord())
		{
			$_ticketidlist[] = $dbCore->Record["ticketid"];
		}

		$strticketid = buildIN($_ticketidlist);
		$_customfieldvalues = array();
		if (count($_customfieldidlist))
		{
			$dbCore->query("SELECT `customfieldid`, `typeid`, `fieldvalue` FROM `". TABLE_PREFIX ."customfieldvalues` WHERE `customfieldid` IN (". buildIN($_customfieldidlist) .") AND `typeid` IN (". $strticketid .");");
			while ($dbCore->nextRecord())
			{
				$_customfieldvalues[$dbCore->Record["typeid"]][$dbCore->Record["customfieldid"]] = $dbCore->Record["fieldvalue"];
			}
		}

		$dbCore->query("SELECT t.*, tp.contents AS preview FROM `". TABLE_PREFIX ."tickets` AS t LEFT JOIN `". TABLE_PREFIX ."ticketposts` AS tp ON (tp.ticketpostid = t.lastpostid) WHERE t.ticketid IN (". $strticketid .") ". $sortstatement.";", 2);
		$_tickets = array();
		while ($dbCore->nextRecord(2))
		{
			$_tickets[$dbCore->Record2["ticketid"]] = $dbCore->Record2;
		}
		return $_tickets;
	}
}

/**
* Get the default ticket view for staff
*/
function getDefaultTicketView($staffid)
{
	global $_SWIFT;

	$_ticketviews = getStaffTicketViews($staffid);
	$updatestaffview =false;
	if (!empty($_REQUEST["ticketviewid"]) && isset($_SWIFT["ticketviewcache"][$_REQUEST["ticketviewid"]]))
	{
		$_ticketview = &$_SWIFT["ticketviewcache"][$_REQUEST["ticketviewid"]];
		if ($_ticketview["viewtype"] == VIEW_PUBLIC || ($_ticketview["viewtype"] == VIEW_PRIVATE && $_ticketview["staffid"] == $staffid))
		{
			$_ticketviewid = intval($_REQUEST["ticketviewid"]);

			require_once ("./includes/functions_staff.php");
			updateStaffTicketView($_ticketviewid);
		}
	} else if (!empty($_SWIFT["staffcache"][$staffid]["ticketviewid"])) {
		$_ticketviewid = intval($_SWIFT["staffcache"][$staffid]["ticketviewid"]);
	}

	if (empty($_ticketviewid))
	{
		$_ticketviewid = 1; // Master View
	}

	return $_ticketviewid;
}

/**
 * Perform a simple text replace
 * This should be used when the string does not contain HTML
 * (off by default)
 */
define('STR_HIGHLIGHT_SIMPLE', 1);
 
/**
 * Only match whole words in the string
 * (off by default)
 */
define('STR_HIGHLIGHT_WHOLEWD', 2);
 
/**
 * Case sensitive matching
 * (off by default)
 */
define('STR_HIGHLIGHT_CASESENS', 4);
 
/**
 * Overwrite links if matched
 * This should be used when the replacement string is a link
 * (off by default)
 */
define('STR_HIGHLIGHT_STRIPLINKS', 8);
 
/**
 * Highlight a string in text without corrupting HTML tags
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     3.1.1
 * @param       string          $text           Haystack - The text to search
 * @param       array|string    $needle         Needle - The string to highlight
 * @param       bool            $options        Bitwise set of options
 * @param       array           $highlight      Replacement string
 * @return      Text with needle highlighted
 */
function str_highlight($text, $needle, $options = null, $highlight = null)
{
    // Default highlighting
    if ($highlight === null) {
        $highlight = '<strong>\1</strong>';
    }
 
    // Select pattern to use
    if ($options & STR_HIGHLIGHT_SIMPLE) {
        $pattern = '#(%s)#';
        $sl_pattern = '#(%s)#';
    } else {
        $pattern = '#(?!<.*?)(%s)(?![^<>]*?>)#';
        $sl_pattern = '#<a\s(?:.*?)>(%s)</a>#';
    }
 
    // Case sensitivity
    if (!($options & STR_HIGHLIGHT_CASESENS)) {
        $pattern .= 'i';
        $sl_pattern .= 'i';
    }
 
    $needle = (array) $needle;
    foreach ($needle as $needle_s) {
        $needle_s = preg_quote($needle_s);
 
        // Escape needle with optional whole word check
        if ($options & STR_HIGHLIGHT_WHOLEWD) {
            $needle_s = '\b' . $needle_s . '\b';
        }
 
        // Strip links
        if ($options & STR_HIGHLIGHT_STRIPLINKS) {
            $sl_regex = sprintf($sl_pattern, $needle_s);
            $text = preg_replace($sl_regex, '\1', $text);
        }
 
        $regex = sprintf($pattern, $needle_s);
        $text = preg_replace($regex, $highlight, $text);
    }
 
    return $text;
}

/**
* Generates select box for status
*/
function generateStatusSelectBox($_departmentid, $_ticketstatusid = false)
{
	global $_SWIFT;
	$_gridset = &$_SWIFT["ticketgridcache"][$_SWIFT["staff"]["staffid"]];

	$_index=0;
	foreach ($_SWIFT["statuscache"] as $key=>$val)
	{
		if ($val["departmentid"] == 0 || $val["departmentid"] == $_departmentid)
		{
			$_statusajax .= 'statuslist['.$_index.'] = new Array();';
			$_statusajax .= 'statuslist['.$_index.'][0] = "'. intval($val['ticketstatusid']) .'";';
			$_statusajax .= 'statuslist['.$_index.'][1] = "'. addslashes(htmlspecialchars($val['title'])) .'";';
			$_statusajax .= 'statuslist['.$_index.'][3] = '. iif(($_gridset["rnticketstatusid"]==$val["ticketstatusid"]&&!empty($_gridset["rnticketstatusid"]))||(empty($_gridset["rnticketstatusid"])&&$val["ticketstatusid"]==$_ticket["ticketstatusid"]), "true", 'false') .';';
			$_statusoptions .= '<option value="'. intval($val["ticketstatusid"]) .'" style="color:'. $val["statuscolor"] .'"'. iif($_ticketstatusid==$val["ticketstatusid"], " selected") .'>'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
			$_poststatusoptions .= '<option value="'. intval($val["ticketstatusid"]) .'" style="color:'. $val["statuscolor"] .'"'. iif(($_gridset["rnticketstatusid"]==$val["ticketstatusid"]&&!empty($_gridset["rnticketstatusid"]))||(empty($_gridset["rnticketstatusid"])&&$val["ticketstatusid"]==$_ticket["ticketstatusid"]), " selected") .'>'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
			$_index++;
		}
	}
	$_statusselect = '<select name="'.$prefix.'tt_ticketstatusid" class="swiftselect">'. $_statusoptions .'</select>'.SWIFT_CRLF;
	$_poststatusselect = '<select name="'.$prefix.'tt_ticketstatusid" class="swiftselect">'. $_poststatusoptions .'</select>'.SWIFT_CRLF;

	return array("_statusselect" => $_statusselect, "_poststatusselect" => $_poststatusselect, '_statusajax' => $_statusajax);
}

/**
* Generate Select Boxes
*/
function generateTicketSelectBoxes($_ticket, $prefix = '', $javascriptadd = false, $customform = '')
{
	global $_SWIFT;

	$_gridset = &$_SWIFT["ticketgridcache"][$_SWIFT["staff"]["staffid"]];

	unset($_staffoptions); unset($_departmentoptions); unset($_statusoptions); unset($_priorityoptions); unset($_flagoptions);
	$_staffoptions = '<option value="0"'. iif(!$_ticket["ownerstaffid"], " selected") .'>'. $_SWIFT["language"]["unassigned"] .'</option>'.SWIFT_CRLF;
	$_poststaffoptions .= '<option value="0"'. iif(!$_ticket["ownerstaffid"], " selected") .'>'. $_SWIFT["language"]["unassigned"] .'</option>'.SWIFT_CRLF;
	if ($prefix == 'fu')
	{
		$_staffoptions = '<option value="-1" selected>'. $_SWIFT["language"]["followupnochange"] .'</option>'.SWIFT_CRLF;
		$_poststaffoptions = '<option value="-1" selected>'. $_SWIFT["language"]["followupnochange"] .'</option>'.SWIFT_CRLF;
		$_staffoptions .= '<option value="0">'. $_SWIFT["language"]["unassigned"] .'</option>'.SWIFT_CRLF;
		$_poststaffoptions .= '<option value="0">'. $_SWIFT["language"]["unassigned"] .'</option>'.SWIFT_CRLF;
	}
	foreach ($_SWIFT["staffcache"] as $key=>$val)
	{
		if ($prefix == 'fu')
		{
			$_staffoptions .= '<option value="'. intval($val["staffid"]) .'">'. htmlspecialchars($val["fullname"]) .'</option>'.SWIFT_CRLF;
			$_poststaffoptions .= '<option value="'. intval($val["staffid"]) .'">'. htmlspecialchars($val["fullname"]) .'</option>'.SWIFT_CRLF;
		} else {
			$_staffoptions .= '<option value="'. intval($val["staffid"]) .'"'. iif($_ticket["ownerstaffid"]==$val["staffid"], " selected") .'>'. htmlspecialchars($val["fullname"]) .'</option>'.SWIFT_CRLF;
			$_poststaffoptions .= '<option value="'. intval($val["staffid"]) .'"'. iif(($_gridset["rnsetowner"]==1&&$val["staffid"]==$_SWIFT["staff"]["staffid"])||(empty($_gridset["rnsetowner"])&&$_ticket["ownerstaffid"]==$val["staffid"]), " selected") .'>'. htmlspecialchars($val["fullname"]) .'</option>'.SWIFT_CRLF;
		}
	}
	$_staffselect = '<select name="'.$prefix.'tt_staffid" class="swiftselect">'. $_staffoptions .'</select>'.SWIFT_CRLF;
	$_poststaffselect = '<select name="'.$prefix.'tt_staffid" class="swiftselect">'. $_poststaffoptions .'</select>'.SWIFT_CRLF;

	if ($prefix == 'fu')
	{
		$_departmentoptions = '<option value="-1" selected>'. $_SWIFT["language"]["followupnochange"] .'</option>'.SWIFT_CRLF;
		$_statusoptions = '<option value="-1" selected>'. $_SWIFT["language"]["followupnochange"] .'</option>'.SWIFT_CRLF;
		$_priorityoptions = '<option value="-1" selected>'. $_SWIFT["language"]["followupnochange"] .'</option>'.SWIFT_CRLF;
	}
	foreach ($_SWIFT["departmentcache"] as $key=>$val)
	{
		if ($val["departmentmodule"] == MODULE_TICKETS)
		{
			if ($prefix == 'fu')
			{
				$_departmentoptions .= '<option value="'. intval($val["departmentid"]) .'">'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
			} else {
				$_departmentoptions .= '<option value="'. intval($val["departmentid"]) .'"'. iif($_ticket["departmentid"]==$val["departmentid"], " selected") .'>'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
			}
		}
	}
	$_departmentselect = '<select name="'.$prefix.'tt_departmentid"'. iif($javascriptadd==true, ' onChange="javascript: updateTicketStatusDiv(\''. intval($_ticket["departmentid"]) .'\', \''. intval($_ticket["ticketstatusid"]) .'\', \''. $customform .'\', \''. intval($_ticket["ticketid"]) .'\', \''. $_prefix.'tt_ticketstatusid'.'\');"') .' class="swiftselect">'. $_departmentoptions .'</select>'.SWIFT_CRLF;

	$_index=0;
	foreach ($_SWIFT["statuscache"] as $key=>$val)
	{
		$_statusajax .= 'statuslist['.$_index.'][0] = "'. intval($val['ticketstatusid']) .'";';
		$_statusajax .= 'statuslist['.$_index.'][1] = "'. addslashes(htmlspecialchars($val['title'])) .'";';
		if ($prefix == 'fu')
		{
			$_statusoptions .= '<option value="'. intval($val["ticketstatusid"]) .'" style="color:'. $val["statuscolor"] .'">'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
			$_poststatusoptions .= '<option value="'. intval($val["ticketstatusid"]) .'" style="color:'. $val["statuscolor"] .'">'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
		} else {
			$_statusoptions .= '<option value="'. intval($val["ticketstatusid"]) .'" style="color:'. $val["statuscolor"] .'"'. iif($_ticket["ticketstatusid"]==$val["ticketstatusid"], " selected") .'>'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
			$_poststatusoptions .= '<option value="'. intval($val["ticketstatusid"]) .'" style="color:'. $val["statuscolor"] .'"'. iif(($_gridset["rnticketstatusid"]==$val["ticketstatusid"]&&!empty($_gridset["rnticketstatusid"]))||(empty($_gridset["rnticketstatusid"])&&$val["ticketstatusid"]==$_ticket["ticketstatusid"]), " selected") .'>'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
		}
		$_index++;
	}
	$_statusselect = '<select name="'.$prefix.'tt_ticketstatusid" class="swiftselect">'. $_statusoptions .'</select>'.SWIFT_CRLF;
	$_poststatusselect = '<select name="'.$prefix.'tt_ticketstatusid" class="swiftselect">'. $_poststatusoptions .'</select>'.SWIFT_CRLF;

	foreach ($_SWIFT["prioritycache"] as $key=>$val)
	{
		if ($prefix == 'fu')
		{
			$_priorityoptions .= '<option value="'. intval($val["priorityid"]) .'" style="background:'. $val["bgcolorcode"] .';color:'. $val["frcolorcode"] .'">'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
		} else {
			$_priorityoptions .= '<option value="'. intval($val["priorityid"]) .'" style="background:'. $val["bgcolorcode"] .';color:'. $val["frcolorcode"] .'"'. iif($_ticket["priorityid"]==$val["priorityid"], " selected") .'>'. htmlspecialchars($val["title"]) .'</option>'.SWIFT_CRLF;
		}
	}
	$_priorityselect = '<select name="'.$prefix.'tt_priorityid" class="swiftselect">'. $_priorityoptions .'</select>'.SWIFT_CRLF;

	return array("_priorityselect" => $_priorityselect, "_statusselect" => $_statusselect, "_poststatusselect" => $_poststatusselect, "_departmentselect" => $_departmentselect, "_poststaffselect" => $_poststaffselect, "_staffselect" => $_staffselect, '_statusajax' => $_statusajax);
}

/**
* Render the Split Field View
*/
function renderSplitFields($infolist, $row1class, $row2class)
{
	if (!_is_array($infolist))
	{
		return false;
	}
	$cnt = $index = 0;
	$indexmod = count($infolist)%2;
	if ($indexmod)
	{
		$infolist[] = array("&nbsp;", "&nbsp;");
	}
	$lastindex = count($infolist)-1;
	$colarray = array();
	for ($ii=0; $ii<count($infolist); $ii++)
	{
		$colarray[$index]["align"] = "left";
		$colarray[$index]["valign"] = "top";
		$colarray[$index]["width"] = "25%";
		$colarray[$index]["nowrap"] = true;
		$colarray[$index]["value"] = '<span class="tabletitle">'.$infolist[$ii][0]."</span>";
		$colarray[$index]["class"] = iif($infolist[$ii][0]=="&nbsp;", $row2class, $row1class);
		$index++;
		$colarray[$index]["align"] = "left";
		$colarray[$index]["valign"] = "top";
		$colarray[$index]["nowrap"] = true;
		$colarray[$index]["width"] = "25%";
		$colarray[$index]["value"] = $infolist[$ii][1];
		$colarray[$index]["class"] = $row2class;
		$cnt++; $index++;

		if ($cnt == 2 || $ii == $lastindex)
		{
			printDataRow($colarray);
			$colarray = array();
			$index = 0;
			$cnt=0;
		}
	}
}

function smallPagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = TRUE)
{
	global $lang, $_SWIFT;
	//&offset=10

	$total_pages = ceil($num_items/$per_page);
	if($total_pages == 1 || empty($total_pages))
	{
		return "";
	}

	$on_page = floor($start_item / $per_page) + 1;

	$page_string = "";

	if( $total_pages > 8 )
	{

		$init_page_max = ( $total_pages > 2 ) ? 2 : $total_pages;

		for($i = 1; $i < $init_page_max + 1; $i++)
		{
			$page_string .= ($i == $on_page) ? "$i" : "<a href=\"" . $base_url . "&amp;offset=" . ( ( $i - 1 ) * $per_page ) . "\">$i</a>";
			if( $i <  $init_page_max )
			{
				$page_string .= ", ";
			}
		}

		if( $total_pages > 2 )
		{
			if( $on_page > 1  && $on_page < $total_pages )
			{
				$page_string .= ( $on_page > 4 ) ? " ... " : ", ";

				$init_page_min = ( $on_page > 3 ) ? $on_page : 4;
				$init_page_max = ( $on_page < $total_pages - 3 ) ? $on_page : $total_pages - 3;

				for($i = $init_page_min - 1; $i < $init_page_max + 2; $i++)
				{
					$page_string .= ($i == $on_page) ? "$i" : "<a href=\"" . $base_url . "&amp;offset=" . ( ( $i - 1 ) * $per_page ) . "\">$i</a>";
					if( $i <  $init_page_max + 1 )
					{
						$page_string .= ", ";
					}
				}

				$page_string .= ( $on_page < $total_pages - 3 ) ? " ... " : ", ";
			}
			else
			{
				$page_string .= " ... ";
			}

			for($i = $total_pages - 1; $i < $total_pages + 1; $i++)
			{
				$page_string .= ($i == $on_page) ? "$i"  : "<a href=\"" . $base_url . "&amp;offset=" . ( ( $i - 1 ) * $per_page ) . "\">$i</a>";
				if( $i <  $total_pages )
				{
					$page_string .= ", ";
				}
			}
		}
	}
	else
	{
		for($i = 1; $i < $total_pages + 1; $i++)
		{
			$page_string .= ($i == $on_page) ? "$i" : "<a href=\"" . $base_url . "&amp;offset=" . ( ( $i - 1 ) * $per_page ) . "\">$i</a>";
			if( $i <  $total_pages )
			{
				$page_string .= ", ";
			}
		}
	}
	$start_item++;
	$on_page = floor($start_item / $per_page) + 1;
	//if( $add_prevnext_text ) {
		if($on_page > 1) {
			$page_string = " <a href=\"" . $base_url . "&amp;offset=" . (($on_page - 2) * $per_page) . "\">" . "&laquo;" . "</a>&nbsp;&nbsp;" . $page_string;
		}
		if($on_page < $total_pages) {
//			$page_string .= "&nbsp;&nbsp;<a href=\"" . $base_url . "&amp;offset=" . ($on_page * $per_page) . "\">" . "&raquo;" . "</a>";
		}
	//}
	if (!empty($page_string))
	{
		$page_string  = "&nbsp;&nbsp;(<img src='".$_SWIFT["themepath"]."icon_page.gif'>" . " " . $page_string.")";
	}
	return $page_string;
}
?>